package com.zhiyou.app.shop.manager.action;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.zhiyou.app.shop.common.AycshopException;
import com.zhiyou.app.shop.common.BaseAction;
import com.zhiyou.app.shop.common.InnerObject;
import com.zhiyou.app.shop.common.util.DateUtil;
import com.zhiyou.app.shop.common.util.MD5;
import com.zhiyou.app.shop.common.util.Page;
import com.zhiyou.app.shop.manager.dao.pojo.Comment;
import com.zhiyou.app.shop.manager.dao.pojo.DeliveryAddress;
import com.zhiyou.app.shop.manager.dao.pojo.Goods;
import com.zhiyou.app.shop.manager.dao.pojo.GoodsCategory;
import com.zhiyou.app.shop.manager.dao.pojo.GoodsImg;
import com.zhiyou.app.shop.manager.dao.pojo.GoodsOrder;
import com.zhiyou.app.shop.manager.dao.pojo.OrderDetail;
import com.zhiyou.app.shop.manager.dao.pojo.PayOrder;
import com.zhiyou.app.shop.manager.dao.pojo.Shop;
import com.zhiyou.app.shop.manager.dao.pojo.ShoppingTrolley;
import com.zhiyou.app.shop.manager.dao.pojo.UserDetail;
import com.zhiyou.app.shop.manager.service.IGoodsManageService;
import com.zhiyou.app.shop.manager.service.IOrderService;
import com.zhiyou.app.shop.manager.service.IShopManageService;
import com.zhiyou.app.shop.manager.service.ISysManageService;

public class AppServiceAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	@Autowired
	private IGoodsManageService goodsService;
	@Autowired
	private IShopManageService shopService;
	@Autowired
	private ISysManageService sysManageService;
	@Autowired
	private IOrderService orderService;
	
	private UserDetail ud = new UserDetail();
	private String userId;
	private String encodeUserId;
	private Goods goods = new Goods();
	private Shop shop = new Shop();
	private Comment comment = new Comment();
	private ShoppingTrolley trolley = new ShoppingTrolley();
	private DeliveryAddress deliveryAddress = new DeliveryAddress();
	private GoodsOrder goodsOrder = new GoodsOrder();
	private PayOrder payOrder = new PayOrder();
	private String orderJson;
	
	@Override
	public UserDetail getCurrentUser(){
		if(StringUtils.isBlank(userId) || (StringUtils.isBlank(encodeUserId)
				|| !MD5.encrypt(userId).equalsIgnoreCase(encodeUserId))){
			
			throw new AycshopException("shopManage.request.invalidate");
			
		}else{
			UserDetail ud = new UserDetail();
			ud.setId(userId);
			//ud.setRole(Short.valueOf("0"));
			return  ud;
		}
	}
	
	public String doLogin(){
		this.printJSON(getResponse(), new InnerObject(){
			public void execute(JsonObject json) {
				UserDetail user = sysManageService.loginAuth(ud.getLoginName(), ud.getPassword());
				json.addProperty("userId", user.getId());
				json.addProperty("userFullName", user.getFullName());
			}
		});
		return null;
	}
	
	/**
	 * 商城分类获取接口
	 * @return
	 */
	public String goodsCategory(){
		this.printJSON(getResponse(), new InnerObject(){
			public void execute(JsonObject json) {
				List<GoodsCategory> catList = sysManageService.getAllGoodsCats();
				JsonArray array = new JsonArray();
				for(GoodsCategory cat : catList){
					JsonObject gs = new JsonObject();
					gs.addProperty("id", cat.getId());
					gs.addProperty("name",  cat.getName());
					array.add(gs);
				}
				json.add("goodsCategorys", array);
			}
		});
		return null;
	}
	
	/**
	 * 商品列表获取接口|搜索商品接口|获取指定商家商品接口
	 * @return
	 */
	public String findGoodsWithPage(){
		this.printJSON(getResponse(), new InnerObject(){
			public void execute(JsonObject json) {
				Page page = getInitedPage();
				goodsService.queryGoodsWithPage(page , goods, Order.desc("hitCount"));
				jsonPageInit(json, page);
				JsonArray array = new JsonArray();
				if(null != page.getResult() && page.getResult().size() > 0){
					List<Goods> list = page.getResult();
					for(Goods goods : list){
						JsonObject gs = new JsonObject();
						gs.addProperty("id", goods.getId());
						gs.addProperty("name", goods.getName());
						gs.addProperty("img", goods.getFirstImg());
						gs.addProperty("price", goods.getPrice());
						gs.addProperty("describe", goods.getRemark());
						array.add(gs);
					}
				}
				json.add("goods", array);
			}
		});
		return null;
	}
	
	/**
	 * 商品详细内容获取接口,需要传入goods.id
	 * @return
	 */
	public String findGoodsById(){
		final UserDetail ud = this.getCurrentUser();
		this.printJSON(getResponse(), new InnerObject(){
			public void execute(JsonObject json) {
				Goods gds = goodsService.findGoodsWithShopUserAndImgs(goods.getId());
				json.addProperty("goodsId", gds.getId());
				json.addProperty("shopUserId", gds.getShop().getUserDetail().getId());
				/**商品图片**/
				JsonArray array = new JsonArray();
				json.add("goodsImgs", array);
				Iterator<GoodsImg> it = gds.getGoodsImgs().iterator();
				while(it.hasNext()){
					GoodsImg img = it.next();
					JsonObject goodsImg = new JsonObject();
					goodsImg.addProperty("imgUrl",img.getImgPath());
					array.add(goodsImg);
				}
				json.addProperty("goodsName", gds.getName());
				json.addProperty("goodsInfo", gds.getRemark());
				json.addProperty("salesPromotionInfo", gds.getSalesPromotionInfo());
				json.addProperty("shareInfo", gds.getShareInfo());
				
				//增加商品浏览记录
				goodsService.saveGoodsVisitLog(goods, ud);
			}
		});
		return null;
	}
	
	/**
	 * 商家信息接口,需要传入shop.id
	 * @return
	 */
	public String findShopInfo(){
		this.printJSON(getResponse(), new InnerObject(){
			public void execute(JsonObject json) {
				Page page = getInitedPage();
				Shop s = shopService.findShopById(shop.getId());
				json.addProperty("shopImg", s.getImgPath());
				json.addProperty("shopUserId", s.getUserDetail().getId());
				json.addProperty("shopName", s.getName());
			}
		});
		return null;
	}
	
	/**
	 * 收藏商品
	 * @return
	 */
	public String addMyFavGoods(){
		final UserDetail ud = this.getCurrentUser();
		this.printJSON(getResponse(), new InnerObject(){
			public void execute(JsonObject json) {
				goodsService.addMyFavGoods(ud, goods);
			}
		});
		return null;
	}
	
	/**
	 * 收藏商铺
	 * @return
	 */
	public String addMyFavShop(){
		final UserDetail ud = this.getCurrentUser();
		this.printJSON(getResponse(), new InnerObject(){
			public void execute(JsonObject json) {
				shopService.addMyFavShop(ud, shop);
			}
		});
		return null;
	}
	
	/**收藏商品列表获取接口
	 * @return
	 */
	public String findMyFavGoods(){
		this.printJSON(getResponse(), new InnerObject(){
			public void execute(JsonObject json) {
				Page page = getInitedPage();
				goodsService.findMyFavGoodsByPage(page, getCurrentUser(), Order.desc("createDate"));
				jsonPageInit(json, page);
				JsonArray array = new JsonArray();
				if(null != page.getResult() && page.getResult().size() > 0){
					List<Goods> list = page.getResult();
					for(Goods goods : list){
						JsonObject gs = new JsonObject();
						gs.addProperty("id", goods.getId());
						gs.addProperty("name", goods.getName());
						gs.addProperty("img", goods.getFirstImg());
						gs.addProperty("price", goods.getPrice());
						array.add(gs);
					}
				}
				json.add("goods", array);
				
			}
		});
		return null;
	}
	
	/**收藏商铺列表获取接口
	 * @return
	 */
	public String findMyFavShop(){
		this.printJSON(getResponse(), new InnerObject(){
			public void execute(JsonObject json) {
				Page page = getInitedPage();
				shopService.findMyFavShopByPage(page, getCurrentUser(),  Order.desc("createDate"));
				jsonPageInit(json, page);
				JsonArray array = new JsonArray();
				if(null != page.getResult() && page.getResult().size() > 0){
					List<Shop> list = page.getResult();
					for(Shop shop : list){
						JsonObject gs = new JsonObject();
						gs.addProperty("id", shop.getId());
						gs.addProperty("name", shop.getName());
						gs.addProperty("img", shop.getImgPath());
						array.add(gs);
					}
				}
				json.add("shops", array);
			}
		});
		return null;
	}
	
	/**添加商品评论接口
	 * @return
	 */
	public String saveGoodsComment(){
		this.printJSON(getResponse(), new InnerObject(){
			public void execute(JsonObject json) {
				comment.setCommentUser(getCurrentUser());
				goodsService.saveGoodsComment(comment);
			}
		});
		return null;
	}
	
	/**商品评论列表接口
	 * @return
	 */
	public String findCommentsByGoods(){
		this.printJSON(getResponse(), new InnerObject(){
			public void execute(JsonObject json) {
				Page page = getInitedPage();
				goodsService.findCommentsByGoods(page, goods);
				jsonPageInit(json, page);
				JsonArray array = new JsonArray();
				if(null != page.getResult() && page.getResult().size() > 0){
					List<Comment> list = page.getResult();
					for(Comment comment : list){
						JsonObject gs = new JsonObject();
						//TODO 目前尚无userImg属性,系统整合的时候应该会有了吧
						gs.addProperty("userImg", comment.getCommentUser().getId());
						gs.addProperty("userFullName", comment.getCommentUser().getFullName());
						gs.addProperty("pubTime", DateUtil.simpleDateFormat(comment.getCommentDate()));
						gs.addProperty("text", comment.getText());
						array.add(gs);
					}
				}
				json.add("comments", array);
			}
		});
		return null;
	}
	
	/**
	 * 添加购物车接口
	 * @return
	 */
	public String saveShoppingTrolley(){
		this.printJSON(getResponse(), new InnerObject() {
			public void execute(JsonObject json) {
				trolley.setUserDetail(getCurrentUser());
				goodsService.saveShoppingTrolley(trolley);
			}
		});
		return null;
	}
	
	/**
	 * 修改购物车接口
	 * @return
	 */
	public String updateShoppingTrolley(){
		this.printJSON(getResponse(), new InnerObject() {
			public void execute(JsonObject json) {
				System.out.println(trolley.getId());
				goodsService.updateShoppingTrolley(trolley.getId(), trolley.getAmount());
			}
		});
		return null;
	}
	
	/**
	 * 删除购物车商品接口
	 * @return
	 */
	public String deleteShoppingTrolley(){
		this.printJSON(getResponse(), new InnerObject() {
			public void execute(JsonObject json) {
				goodsService.deleteShoppingTrolley(trolley.getId());
			}
		});
		return null;
	}
	
	/**
	 *购物车商品列表接口
	 * @return
	 */
	public String findMyShoppingTrolley(){
		this.printJSON(getResponse(), new InnerObject() {
			public void execute(JsonObject json) {
				List<ShoppingTrolley> list = goodsService.findShoppingTrolleyByUser(getCurrentUser());
				JsonArray array = new JsonArray();
				json.add("goods", array);
				if(! list.isEmpty()){
					for(ShoppingTrolley trolley : list){
						JsonObject gs = new JsonObject();
						gs.addProperty("trolleyId", trolley.getId());
						gs.addProperty("goodsAmount", trolley.getAmount());
						gs.addProperty("goodsId", trolley.getGoods().getId());
						gs.addProperty("goodsPrice", trolley.getGoods().getPrice());
						gs.addProperty("goodsName", trolley.getGoods().getName());
						gs.addProperty("goodsImg", trolley.getGoods().getFirstImg());
						gs.addProperty("shopId", trolley.getGoods().getShop().getId());
						array.add(gs);
					}
				}
			}
		});
		return null;
	}
	
	/**
	 * 用户收货地址设置接口
	 * @return
	 */
	public String saveDeliveryAddress(){
		this.printJSON(getResponse(), new InnerObject(){
			public void execute(JsonObject json) {
				deliveryAddress.setUserDetail(getCurrentUser());
				sysManageService.saveDeliveryAddress(deliveryAddress);
			}
		});
		return null;
	}
	/**
	 * 生成订单接口
	 * @return
	 */
	public String saveOrder(){
		this.printJSON(getResponse(), new InnerObject(){
			public void execute(JsonObject json) {
				String orderId = orderService.saveOrderFromJsonStr(orderJson, getCurrentUser());
				json.addProperty("orderId", orderId);
			}
		});
		return null;
	}
	
	/**
	 * 支付宝支付结果通知url 
	 * @return
	 */
	public String updateOrderPayStatus(){
		this.printJSON(getResponse(), new InnerObject(){
			public void execute(JsonObject json) {
				//TODO if success
				orderService.updateOrderPayStatus(payOrder.getId(), getCurrentUser().getId());
			}
		});
		return null;
	}
	
	/**
	 * 已付款列表接口
	 * @return
	 */
	public String findMyPayedOrder(){
		this.printJSON(getResponse(), new InnerObject(){
			public void execute(JsonObject json) {
				goodsOrder.setUserDetail(getCurrentUser());
				goodsOrder.setIsPay(Boolean.TRUE);
				Page page = getInitedPage();
				orderService.findGoodsOrderForApp(page, goodsOrder);
				jsonPageInit(json, page);
				JsonArray odArray = new JsonArray();
				json.add("orders", odArray);
				List<GoodsOrder> listOrder = page.getResult();
				if(! listOrder.isEmpty()){
					for(GoodsOrder order : listOrder){//处理某一个订单
						JsonObject odJson = new JsonObject();
						odJson.addProperty("orderId", order.getId());
						odJson.addProperty("orderPrice", order.getOrderPrice());
						odJson.addProperty("createDate", DateUtil.simpleDateFormat(order.getCreateDate()));
						JsonArray goodsArray = new JsonArray();
						odJson.add("goodsArray", goodsArray);
						odArray.add(odJson);
						Set<OrderDetail> ds = order.getOrderDetails();
						Iterator<OrderDetail> it = ds.iterator();
						while(it.hasNext()){//订单商品循环
							JsonObject goodsJson = new JsonObject();
							OrderDetail od = it.next();
							goodsJson.addProperty("goodsId", od.getGoodsId());
							goodsJson.addProperty("goodsName", od.getGoodsName());
							goodsJson.addProperty("goodsImg", od.getGoodsImg());
							goodsJson.addProperty("goodsPrice", od.getGoodsPrice());
							goodsJson.addProperty("goodsAmount", od.getAmount());
							goodsArray.add(goodsJson);
						}
					}
				}
				
			}
		});
		return null;
	}
	
	/**将分页信息填充到json中**/
	protected void jsonPageInit(JsonObject json, Page page) {
		json.addProperty("pageCount", page.getTotalPageCount());
		json.addProperty("recordCount", page.getTotalCount());
		json.addProperty("currentPageNo", page.getPageNo());
	}
	
	
	public UserDetail getUd() {
		return ud;
	}

	public void setUd(UserDetail ud) {
		this.ud = ud;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getEncodeUserId() {
		return encodeUserId;
	}

	public void setEncodeUserId(String encodeUserId) {
		this.encodeUserId = encodeUserId;
	}

	public Goods getGoods() {
		return goods;
	}
	
	public void setGoods(Goods goods) {
		this.goods = goods;
	}

	public Shop getShop() {
		return shop;
	}

	public void setShop(Shop shop) {
		this.shop = shop;
	}

	public Comment getComment() {
		return comment;
	}

	public void setComment(Comment comment) {
		this.comment = comment;
	}

	public ShoppingTrolley getTrolley() {
		return trolley;
	}

	public void setTrolley(ShoppingTrolley trolley) {
		this.trolley = trolley;
	}

	public DeliveryAddress getDeliveryAddress() {
		return deliveryAddress;
	}

	public void setDeliveryAddress(DeliveryAddress deliveryAddress) {
		this.deliveryAddress = deliveryAddress;
	}

	public GoodsOrder getGoodsOrder() {
		return goodsOrder;
	}

	public void setGoodsOrder(GoodsOrder goodsOrder) {
		this.goodsOrder = goodsOrder;
	}

	public String getOrderJson() {
		return orderJson;
	}

	public void setOrderJson(String orderJson) {
		this.orderJson = orderJson;
	}

	public PayOrder getPayOrder() {
		return payOrder;
	}

	public void setPayOrder(PayOrder payOrder) {
		this.payOrder = payOrder;
	}
}
